package com.example.utils;

import org.slf4j.Logger;

import java.net.InetAddress;
import java.net.UnknownHostException;

/*
 * @className: IPUtils
 * @author: chentao
 * @date: 2025/2/21 下午5:08
 * @Version: 1.0
 * @description:
 */
public class IPUtils {

    static Logger logger = org.slf4j.LoggerFactory.getLogger(IPUtils.class);

    public static String getLocalIP() {
        String ip = "127.0.0.1";
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            ip = localHost.getHostAddress();
        } catch (UnknownHostException e) {
            logger.warn("获取本地IP异常: " + e.getMessage());
        }
        return ip;
    }

    /****
     * 把IP地址转成10进制的整型
     * @param ipAddress
     * @return
     */
    public static long toDecimal(String ipAddress) {
        String[] parts = ipAddress.split("\\.");
        long result = 0;
        for (int i = 0; i < parts.length; i++) {
            int value = Integer.parseInt(parts[i]);
            result += value << (24 - (i * 8));
        }
        return result;
    }

    /****
     * 把整型ip地址和端口合并
     * @param ipAddress
     * @param port
     * @return
     */
    public static long combineIpAndPort(String ipAddress, int port) {
        long ipAsLong = toDecimal(ipAddress);
        return (ipAsLong << 16) | (port & 0xFFFF);
    }

    /****
     * 把整型IP转成分点式
     * @param decimalIpAddress
     * @return
     */
    public static String fromDecimal(long decimalIpAddress) {
        StringBuilder ipAddressBuilder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int shift = 24 - (i * 8);
            int value = (int) ((decimalIpAddress >> shift) & 0xFF);
            ipAddressBuilder.append(value);
            if (i < 3) {
                ipAddressBuilder.append(".");
            }
        }
        return ipAddressBuilder.toString();
    }

    /****
     * 把整型的IP端口数据转成数组
     * @param combined
     * @return
     */
    public static String[] splitIpAndPort(long combined) {
        long ipAsLong = combined >> 16;
        int port = (int) (combined & 0xFFFF);
        String ipAddress = fromDecimal(ipAsLong);
        return new String[]{ipAddress, String.valueOf(port)};
    }

    /***
     * 获取服务端的IP地址和端口号
     * @return
     */
    public static long getServer() {
        return combineIpAndPort(getLocalIP(), Integer.parseInt(System.getProperty("maven.tomcat.port")));
    }
}
